<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="tenantId" v-if="tenantEnabled">
      <el-select v-model="loginForm.tenantId" filterable placeholder="请选择/输入公司名称" style="width: 100%">
        <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
        <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
      </el-select>
    </el-form-item>
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：admin / user" @keyup.enter="login(loginFormRef)">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="密码：123456" show-password autocomplete="new-password" @keyup.enter="login(loginFormRef)">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="code" v-if="captchaEnabled">
      <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="login(loginFormRef)">
        <template #prefix><svg-icon icon-class="validCode" /></template>
      </el-input>
      <div class="login-code">
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </div>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { HOME_URL } from "@/config";
import { ElForm } from "element-plus";
import { loginApi, getCodeImg, getTenantList } from "@/api/login";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import { setToken } from "@/utils/auth";
import { LoginData, TenantVO } from "@/api/types";

const router = useRouter();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(false);
const codeUrl = ref("");
const loading = ref(false);
// 租户列表
const tenantList = ref<TenantVO[]>([]);
// pc端固定客户端授权id
const clientId = import.meta.env.VITE_APP_CLIENT_ID;
const loginForm = reactive<LoginData>({
  username: "admin",
  password: "admin123",
  clientId: clientId,
  grantType: "password",
  tenantId: "000000",
  rememberMe: false,
  uuid: ""
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const { data } = await loginApi({ ...loginForm });
      setToken(data.access_token);
      // 2.添加动态路由
      // await initDynamicRouter()
      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);
      // 4.跳转到首页
      router.push(HOME_URL);
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const getCode = async () => {
  const { data } = await getCodeImg();
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data?.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = "data:image/gif;base64," + data.img;
    loginForm.uuid = data.uuid;
  }
};

const getTenant = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.tenantId = tenantList.value[0].tenantId;
    }
  }
};

onMounted(() => {
  getTenant();
  getCode();
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
